#include "xict_cpp/bridge/udp_client.h"

UDPClient::UDPClient() {}

UDPClient::~UDPClient() {
    close(serverSocket);
}

void UDPClient::Init() {
    // 建立一个数据报类型的UDP套接字
    for (int i = 0; i < 3; i++) {
        serverSocket = socket(PF_INET, SOCK_DGRAM, 0);
        if (serverSocket < 0) {
            LOG_F(ERROR, "socket error");
        } else {
            LOG_F(INFO, "socket success");
            break;
        }
    }
}

void UDPClient::SetServerAddr(const char* ip, int port) {
    // 设置服务器地址addrSrv和监听端口
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr =
        inet_addr(ip);   // 设置服务器主机ip地址（与接收方客户端的IP对应）
    server_addr.sin_port = htons(port);   // 发送用的端口
    // 使用bind（）函数绑定监听端口，将socket文件描述符sockSrv与地址类型变量（struct
    //  sockaddr_in ）进行绑定 int bind(int sockfd, const struct sockaddr *addr,
    //  socklen_t addrlen);
    int bind_id =
        bind(serverSocket, (struct sockaddr*)&server_addr, sizeof(server_addr));
    if (bind_id < 0) {
        LOG_F(ERROR, "bind error");
    } else {
        LOG_F(INFO, "bind success");
    }
}

void UDPClient::SetClientAddr(const char* ip, int port) {
    clientSocket           = socket(PF_INET, SOCK_DGRAM, 0);   // 配置模式
    client_addr.sin_family = AF_INET;
    client_addr.sin_addr.s_addr = inet_addr(ip);
    client_addr.sin_port        = htons(port);
}

void UDPClient::sendData(std::string msg) {
    if (sendto(clientSocket, msg.c_str(), msg.length(), 0,
               (struct sockaddr*)&client_addr, sizeof(client_addr)) < 0) {
        LOG_F(ERROR, "sendto error");
    } else {
        LOG_F(INFO, "sendto success");
    }
}

char* UDPClient::ReceiveData() {
    len = sizeof(server_addr);
    recvfrom(serverSocket, recv_info_buf, sizeof(recv_info_buf), 0,
             (struct sockaddr*)&server_addr, &len);
    return recv_info_buf;
}
